package bb;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.HandlebarsTemplateEngine;

public class VertxTest extends AbstractVerticle {

	
	@Override
	public void start() throws Exception {
		
		JDBCClient client = JDBCClient.createShared(vertx, new JsonObject()
				.put("url", "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8")
				.put("driver_class", "com.mysql.jdbc.Driver")
				.put("user", "root")
				.put("password", "root")
				.put("max_pool_size", 30));
		

		Router router = Router.router(vertx);
		router.route("/*.html").handler(StaticHandler.create());//开启静态资源
		//开启jdbc
 		router.route("/*").handler(ctx -> {
 			
 			client.getConnection(con -> {
 				if(con.failed()){
 					System.err.println(con.cause().getMessage());
 				}else{
 					SQLConnection sqlconn = con.result();
 					ctx.put("conn", sqlconn);//加入到ctx
 					ctx.addHeadersEndHandler(down -> sqlconn.close(close -> {
 						if(close.failed()){
 							down.fail(close.cause());
 						}else{
 							down.complete();
 						}
 					}));
 					ctx.next();
 				}
 			});
 			
 		    // In order to use a template we first need to create an engine
 	 	    final HandlebarsTemplateEngine engine = HandlebarsTemplateEngine.create();
 	 	    ctx.put("engine", engine);
 		});
 		
 		
		router.get("/products").handler(this::print2);
		router.get("/page").handler(this::print3);
		router.get("/queryuser").handler(this::queryuser);
		router.get("/hbs").handler(this::hbs);
		router.get("/*").handler(this::print1);

		// 传递方法引用，监听端口
		vertx.createHttpServer().requestHandler(router::accept).listen(8080);
		
/*		
		vertx.createHttpServer().requestHandler(req -> {
			if(req.path().equals("/index")){
				req.response().sendFile("index.html");
			}
		}).listen(8080);*/
	}
	
	public void print1(RoutingContext ctx){
		ctx.response().putHeader("content-type", "text/html").end("Hello World");
	}
	public void print2(RoutingContext ctx){
		ctx.response().putHeader("content-type", "text/html").end("Hi products");
	}
	public void print3(RoutingContext ctx){
		ctx.response().sendFile("index.html");

	}
	public void queryuser(RoutingContext ctx){
		
		StringBuffer sb = new StringBuffer();
		
		SQLConnection connection = ctx.get("conn");
		connection.query("select *from user",rs -> {
			for(JsonArray line : rs.result().getResults()){
				String s = line.encode();
				System.out.println(s);
				sb.append(s);
			}
			ctx.response().putHeader("content-type", "text/html;charset=UTF-8").end(sb.toString());
		});

	}
	
	public void hbs(RoutingContext ctx) {
		
		ctx.put("name", "hbs 渲染");

		// and now delegate to the engine to render it.
		((HandlebarsTemplateEngine) ctx.get("engine")).render(ctx, "templates/index.hbs", res -> {
			if (res.succeeded()) {
				ctx.response().end(res.result());
			} else {
				ctx.fail(res.cause());
			}
		});
	}
 
	

	public static void main(String[] args) {
	    System.setProperty("vertx.cwd", "E:\\work\\atest\\src\\main\\java\\bb");//路径前缀

		Vertx vertx = Vertx.vertx(new VertxOptions().setClustered(false));
		vertx.deployVerticle(VertxTest.class.getName());
	}

}
